// Register Page Component
import React, { useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { Link, useNavigate } from 'react-router-dom';
import { Mail, Key, User, ShieldCheck } from 'lucide-react';
import { API_ENDPOINTS } from '../config/api';

const RegisterPage = () => {
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: '',
    confirmPassword: '',
    emailCode: '',
  });
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [codeLoading, setCodeLoading] = useState(false);
  const [codeSent, setCodeSent] = useState(false);
  const { login } = useAuth();
  const navigate = useNavigate();

  const handleSendCode = async () => {
    if (!formData.email) {
      setError('请输入您的邮箱地址');
      return;
    }
    setCodeLoading(true);
    setError('');

    try {
      const response = await fetch(API_ENDPOINTS.SEND_CODE, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email: formData.email, type: 'REGISTER' }),
      });

      const data = await response.json();

      if (response.ok && data.code === 0) {
        setCodeSent(true);
        // 可以设置一个定时器，比如60秒后才能重新发送
      } else {
        setError(data.message || '验证码发送失败，请稍后再试');
      }
    } catch (err) {
      setError('网络错误，无法发送验证码');
    } finally {
      setCodeLoading(false);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (formData.password !== formData.confirmPassword) {
      setError('两次输入的密码不一致');
      return;
    }
    setLoading(true);
    setError('');

    try {
      const response = await fetch(API_ENDPOINTS.REGISTER, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: formData.username,
          email: formData.email,
          password: formData.password,
          confirmPassword: formData.confirmPassword,
          emailCode: formData.emailCode
        }),
      });

      const data = await response.json();

      if (response.ok && data.code === 200) {
        // 注册成功，保存用户信息和token
        await login(data.data, data.data.token);
        navigate('/profile');
      } else {
        setError(data.message || '注册失败，请稍后再试');
      }
    } catch (err) {
      setError('网络错误，注册失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="auth-page">
      <div className="auth-container">
        <div className="auth-header">
          <h2>创建您的 红小匠·AI 账号</h2>
          <p>已有账号？ <Link to="/login">立即登录</Link></p>
        </div>
        <form onSubmit={handleSubmit} className="auth-form">
          {error && <p className="auth-error">{error}</p>}
          <div className="form-group">
            <User />
            <input type="text" name="username" placeholder="用户名" required onChange={handleChange} />
          </div>
          <div className="form-group">
            <Mail />
            <input type="email" name="email" placeholder="邮箱地址" required onChange={handleChange} />
          </div>
          <div className="form-group code-group">
            <ShieldCheck />
            <input type="text" name="emailCode" placeholder="邮箱验证码" required onChange={handleChange} />
            <button type="button" onClick={handleSendCode} disabled={codeSent || loading || codeLoading}>
              {codeLoading ? '发送中...' : codeSent ? '已发送' : '发送验证码'}
            </button>
          </div>
          <div className="form-group">
            <Key />
            <input type="password" name="password" placeholder="密码" required onChange={handleChange} />
          </div>
          <div className="form-group">
            <Key />
            <input type="password" name="confirmPassword" placeholder="确认密码" required onChange={handleChange} />
          </div>
          <button type="submit" className="auth-button" disabled={loading}>
            {loading ? '注册中...' : '注册'}
          </button>
        </form>
      </div>
    </div>
  );
};

export default RegisterPage; 